package orest.back.achieve;

import orest.common.dao.UserSessionDao;
import orest.common.valueobject.UserSessionInfo;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import orest.common.util.Tools;

/**
 * This class provide relevant operations for user session.
 * Include add, find and delete session object.
 * 
 * @author shilei
 *
 */
public class UserSessionAction extends HttpServlet {

	public void init(ServletConfig config) throws ServletException {
		super.init(config);
	}
	
	public void service(HttpServletRequest request, 
			HttpServletResponse response) throws ServletException, IOException {
		
		String action = request.getParameter("action");
		if (action.equals("add")) {
			addSessionObject(request);
		}
		else if (action.equals("find")) {
			findSessionObject(request);
		}
		else if (action.equals("del")) {
			delSessionObject(request);
		}
	}

        public void addSessionObject(HttpServletRequest request) throws ServletException, IOException {
		
		UserSessionInfo sessionInfo = new UserSessionInfo();
		UserSessionDao obj = new UserSessionDao();
		boolean opReturn = true;
		Tools tool = new Tools();
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		
                if(username != null)
                    username = username;
                if(password != null)
                    password = password;
                
		opReturn = obj.getSessionInfo(username, password, sessionInfo);
                if(!opReturn) {
                    return;
                }       
                HttpSession session = request.getSession();
                session.setAttribute("frontuser", sessionInfo);
	}

	public UserSessionInfo findSessionObject(HttpServletRequest request) throws ServletException, IOException {
		
		HttpSession session = request.getSession();
		Object obj = session.getAttribute("frontuser");
		if (obj != null) {
			return (UserSessionInfo)obj;
		}else {
			return null;
		}
	}
	
	public void delSessionObject(HttpServletRequest request) throws ServletException, IOException {
		
		HttpSession session = request.getSession();
		session.removeAttribute("frontuser");
	}
        
   

        public void addSessionObjectByUserName(HttpServletRequest request) throws ServletException, IOException {

		UserSessionInfo sessionInfo = new UserSessionInfo();
		UserSessionDao obj = new UserSessionDao();
		boolean opReturn = true;
		Tools tool = new Tools();
		String username = request.getParameter("username");
		if(username != null)
                    username = username;

		opReturn = obj.getSessionInfo(username,sessionInfo);
                if(!opReturn) {
                    return;
                }
                HttpSession session = request.getSession();
                session.setAttribute("frontuser", sessionInfo);
	}

}
